import { useEffect, useState } from "react";
import styles from './index.module.sass';


interface ChangeFunction {
    (idx: number): any
}

interface Props {
    /**配置项 */
    list: any[]

    /**值 */
    value?: any

    /**默认选中的值 */
    defaultValue?: any

    /**选项变化时的回调函数 */
    onChange?: ChangeFunction
}

/**
 * 用于首页大屏的按钮单选组
 */
const DashboardRadioButton: React.FC<Props> = ({
    list,
    value,
    defaultValue,
    onChange
}) => {
    console.debug('DashboardRadioButton');

    const [val, setVal] = useState<any>(defaultValue);

    useEffect(() => {
        setVal(value);
    }, [value])

    function handleClick(param: any) {
        if (param !== val) {
            setVal(param);
            onChange && onChange(param);
        }
    }

    const buttonList = list.map((item, idx) => {
        const sassClassName = idx === val ? styles.radioButtonChecked : styles.radioButtonDefault;
        return {
            name: item,
            sassClassName
        }
    });

    return (
        <article className={styles.wrapper}>
            {buttonList.map((item, idx) =>
                <div className={item.sassClassName} key={item.name} onClick={() => { handleClick(idx) }} >{item.name}</div>
            )}
        </article>
    )
}

export default DashboardRadioButton;